﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace wpf_nes
{
    /// <summary>
    /// nes_cpu.xaml 的交互逻辑
    /// </summary>
    public partial class Control_Nes_CPU : UserControl, IWantKnownUpdate
    {
        public Control_Nes_CPU()
        {
            InitializeComponent();
        }

        //当nes 有更新，这里会收到，好刷新UI
        public void Update()
        {
            if (info_watch.IsChecked.Value)
            {
                UpdateState();
            }
        }
        void UpdateState()
        {
            this.info_state.Text = "CPU frame=" + staticfunc.console.Cpu.CPUFrameID + "  PC=0x" + staticfunc.console.Cpu.PC.ToString("X04");
            this.info_reg.Text = "Reg=" + staticfunc.console.Cpu.GetRegisterString();
            this.info_flag.Text = "Flag=" + staticfunc.console.Cpu.GetFlagString();

        }
        void UpdateHotCode()
        {
            var pc = staticfunc.console.Cpu.PC;
            //读取PC往后的16条指令
            for (var i = 0; i < 16; i++)
            {
                var addr = staticfunc.console.Mapper.GetRPGChipAddress(pc);
                if (addr < 0)
                    break;
                var addrstr = pc.ToString("X04");
                var code = ASM6502.DAsm.ReadCode(staticfunc.console.Cartridge.GetRpgRom(), (uint)addr);
                if (code == null)
                    break;
                pc += (ushort)(code.Size);
                ListBoxItem line = hot_code.Items[i] as ListBoxItem;
                line.Content = addrstr + ":" + code.ToString();
            }
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            staticfunc.WantKnownUpdate(this);
        }
        //stop
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            staticfunc.console.Stop = true;
            UpdateState();
        }
        //step
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            staticfunc.console.StepCPU();
            UpdateState();
            UpdateHotCode();
        }
        //go
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            staticfunc.console.Stop = false;

        }

        //reset
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            staticfunc.console.Reset();
            UpdateState();
            UpdateHotCode();

        }
    }
}
